package com.lyc.demo;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

@Slf4j
public class JsonToList {

    private String json;

    /**
     * 将list对象转换成json
     */
    @Before
    public void testListToJson(){
        User user1 = User.builder()
                .id(1)
                .name("zhangsan")
                .build();
        User user2 = User.builder()
                .id(2)
                .name("lisi")
                .build();
        List<User> list = Lists.newArrayList();
        list.add(user1);
        list.add(user2);
        json = JsonMapper.objectToJson(list);
    }

    /**
     * 将json转换成list对象（TypeReference）
     */
    @Test
    public void testJsonToListTypeReference(){
        List<User> list = JsonMapper.jsonToObject(json, new TypeReference<List<User>>() {
        });
        if(list != null){
            User user1 = list.get(0);
            User user2 = list.get(1);
            log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
            log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
        }
    }

    /**
     * 将json转换成list对象
     */
    @Test
    public void testJsonToListClass(){
        List<User> list = JsonMapper.jsonToObject(json, List.class,User.class);
        if(list != null){
            User user1 = list.get(0);
            User user2 = list.get(1);
            log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
            log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
        }
    }

}
